# -*- coding:utf-8 -*-
# File Name:resource.py
# Author:jing
# Date:2018/12/18
from flask import request
from ygframe.db.query import Query
from ygframe.flask_app import YgResource, Sample
from ygframe.logger import logger

from model.mongo_model.resource_info import ResourceInfo, Status
from orm import get_resource_mapper
from util.resource_info_util import get_resource
from interface.resource import Resource as ResourceModel

__author__ = 'jing'

CRITERIA = 'criteria'
UID = 'uid'

RESOURCE_TYPE = 'resource_type'
RESOURCE_NAME = 'resource_name'
RESOURCE_DATA = 'resource_data'
RESOURCE_ID = 'resource_id'
LIMITS = 'limits'
REQUESTS = 'requests'


class Resource(YgResource):

    @classmethod
    def get(cls):
        criteria = request.args.get(CRITERIA)

        # todo get user id
        uid = request.args.get(UID)

        try:
            query = Query.loads(criteria)  # type: Query
        except:
            query = ResourceInfo.query().filter(ResourceInfo.user_id == uid).page_size(20)

        resource_list = []
        for resource_info in query.get():  # type:ResourceInfo
            resource = get_resource(resource_info)
            resource_list.append(resource.get_info_data())
        return cls.success(resource_list=resource_list)

    @classmethod
    def post(cls):
        json_data = request.get_json()
        uid = json_data.get(UID)  # todo get uid
        resource_type = json_data.get(RESOURCE_TYPE)
        resource_data = json_data.get(RESOURCE_DATA)  # type:dict
        resource_data[UID] = uid
        for key in [RESOURCE_NAME, LIMITS, REQUESTS]:
            value = json_data.get(key)
            if value:
                resource_data[key] = value
        get_resource_mapper().get(resource_type).create_info(resource_data)
        logger.info('save resource success')
        return cls.success()

    @classmethod
    def delete(cls):
        json_data = request.get_json()
        uid = json_data.get(UID)  # todo get uid
        resource_id = json_data.get(RESOURCE_ID)
        resource_type = json_data.get(RESOURCE_TYPE)
        resource = get_resource_mapper().get(resource_type)(ResourceInfo(
            user_id=uid,
            resource_id=resource_id
        ))
        if isinstance(resource, ResourceModel):
            resource.release()
        return cls.success()

    __post_request_sample__ = [
        Sample({
            UID: 'user01',
            RESOURCE_TYPE: 'mysql',
            RESOURCE_NAME: 'mysqlname01',
            RESOURCE_DATA: {
                'encoding': 'utf8mb4'
            }
        }),
        Sample({
            UID: 'user01',
            RESOURCE_TYPE: 'redis',
            RESOURCE_NAME: 'redisname01',
            RESOURCE_DATA: {
                'limits': {
                    'memory': '512Mi'
                }
            }
        })
    ]

    __delete_request_sample__ = [
        Sample({
            UID: 'user01',
            RESOURCE_TYPE: 'mysql',
            RESOURCE_ID: 'xxx'
        })
    ]

    __get_request_sample__ = [
        Sample({
            CRITERIA: ResourceInfo.query().filter(
                ResourceInfo.user_id == 'user01',
                ResourceInfo.status.in_([Status.RUNNING, Status.RECEIVED])
            ).page_size(20).sort_by(
                ResourceInfo.apply_date.desc()
            ).dumps()
        })
    ]
